package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import pojo.Address;
import pojo.User;
import service.AddressService;

import javax.servlet.http.HttpServletRequest;
import java.util.Hashtable;
import java.util.List;

@Controller
public class AddressServlet {

    @Autowired
    AddressService addressService;

    @RequestMapping("/getAddress")
    public ModelAndView getAddress(ModelAndView modelAndView, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        int userId = user.getId();
        List<Address> list = addressService.selectAll(userId);

        modelAndView.addObject("addList",list);
        modelAndView.setViewName("/self_info.jsp");
        return modelAndView;
    }

    @RequestMapping("/deleteAddress")
    public String deleteAddress(HttpServletRequest request){
        int id = Integer.parseInt(request.getParameter("id"));

        addressService.deleteAddress(id);

        return "redirect:/getAddress";
    }

    @RequestMapping("/updateAddress")
    public String updateAddress(HttpServletRequest request){
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");

        String detail = request.getParameter("detail");

        int id = Integer.parseInt(request.getParameter("id"));

        Address address  = new Address();
        address.setId(id);
        address.setDetail(detail);
        address.setPhone(phone);
        address.setName(name);

        addressService.updateAddress(address);
        return "redirect:/getAddress";
    }
    @RequestMapping("/defaultAddress")
    public String defaultAddress(HttpServletRequest request){
        int id = Integer.parseInt(request.getParameter("id"));
        User user = (User)request.getSession().getAttribute("user");
        int userId = user.getId();
        addressService.defaultAddress(id,userId);
        return "redirect:/getAddress";

    }
       @RequestMapping("/addAddress")
        public String addAddress(HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("user");

        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");

        Address address = new Address();
        address.setName(name);
        address.setPhone(phone);
        address.setDetail(detail);
        address.setUid(user.getId());
        addressService.addAddress(address);
           return "redirect:/getAddress";
    }
}



















